package com.taotao.service.impl;

import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.IPictureService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Package com.taotao.service.impl
 * @Description:
 * @Author elwyn
 * @Date 2017/9/3 2:00
 * @Email elonyong@163.com
 */
@Service
public class PictureServiceImpl implements IPictureService {
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;

    @Override
    public Map uploadPicture(MultipartFile multipartFile) {
        Map resultMap = new HashMap();
        try {
            String originalFilename = multipartFile.getOriginalFilename();

            String newName = IDUtils.genImageName();
            newName = newName + originalFilename.substring(originalFilename.lastIndexOf("."));
            String imagepath = new DateTime().toString("/yyyy/MM/dd");
            boolean b = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH,
                    imagepath, newName, multipartFile.getInputStream());
            if (!b) {
                resultMap.put("error", 1);
                resultMap.put("message", "文件上传失败");
                return
                        resultMap;
            }
            resultMap.put("error", 0);
            resultMap.put("url", IMAGE_BASE_URL + imagepath + "/" + newName);
            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("error", 1);
            resultMap.put("message", "文件上传异常");
            return resultMap;
        }
    }
}
